package com.xlhj.boot.webservice.ws.client.service;

import com.xlhj.boot.webservice.ws.api.entity.UserInfo;
import com.xlhj.boot.webservice.ws.api.service.UserInfoService;
import com.xlhj.boot.webservice.ws.client.interceptor.ClientLoginInterceptor;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.springframework.stereotype.Component;

/**
 * @Author: caijliu
 * @Date: 06/12/2021 12:12
 * @Description TODO
 * @Vsersion: 0.0.1
 */
@Component
public class UserInfoApiClient {

    private static final String USERNAME = "caijliu";
    private static final String PASSWORD = "xlhj.com";
    private static final String ADDRESS = "http://localhost:8235/services/userInfoService?wsdl";

    /**
     * 使用代理方法
     * @param userInfo
     */
    public void saveUserInfoWithProxy(UserInfo userInfo) {
        JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
        jaxWsProxyFactoryBean.setAddress(ADDRESS);
        jaxWsProxyFactoryBean.setServiceClass(UserInfoService.class);
        jaxWsProxyFactoryBean.getOutInterceptors().add(
                new ClientLoginInterceptor(USERNAME, PASSWORD)
        );
        UserInfoService userInfoService = (UserInfoService) jaxWsProxyFactoryBean.create();
        userInfoService.saveUserInfo(userInfo);
    }

    /**
     * 使用动态代理
     * @param userInfo
     * @throws Exception
     */
    public void saveUserInfoWithDynamic(UserInfo userInfo) throws Exception {
        JaxWsDynamicClientFactory clientFactory = JaxWsDynamicClientFactory.newInstance();
        Client client = clientFactory.createClient(ADDRESS);
        client.getOutInterceptors().add(new ClientLoginInterceptor(USERNAME, PASSWORD));
        client.invoke("saveUserInfo", userInfo);
    }

    public void getUserInfoByIdWithDynamic(Long id) throws Exception {
        JaxWsDynamicClientFactory clientFactory = JaxWsDynamicClientFactory.newInstance();
        Client client = clientFactory.createClient(ADDRESS);
        client.getOutInterceptors().add(new ClientLoginInterceptor(USERNAME, PASSWORD));
        Object[] userInfos = client.invoke("getUserInfoById", id);
        String userInfo = userInfos[0].toString();
        System.out.println(userInfo);
    }
}
